# coding:utf-8
import requests
import json
from enum import Enum
from abc import ABCMeta, abstractmethod
import datetime
import random
import time
from uestc_login import Login
import threading
from util import get_date_str
import logging
import config

logging.basicConfig(filename='./logs/uestc.log', level=logging.INFO)


class Task(object):

    class RequestMethod(Enum):
        GET = 1
        POST = 2

    def __init__(self):
        self.method = Task.RequestMethod.GET
        self.cookies = {}
        self.url = ''
        self.data = {}
        self.interval = 24  # hour
        self.last_run = 0

    @abstractmethod
    def run(self):
        pass

    @abstractmethod
    def runable(self):
        pass

    @abstractmethod
    def init_data(self):
        pass


class TemperatureTask(Task):
    def __init__(self):
        """TemperatureTask"""
        super(TemperatureTask, self).__init__()
        self.url = 'http://eportal.uestc.edu.cn/qljfwapp/sys/lwReportEpidemicStu/mobile/tempReport/T_REPORT_TEMPERATURE_YJS_SAVE.do'
        self.method = self.RequestMethod.POST
        self.last_run = []
        self.init_data()
        self.headers = {}

    def init_data(self):
        """ init cookies and user data """
        self.cookies = Login.load_cookies()
        print(self.cookies)
        user_info_url = "http://eportal.uestc.edu.cn/qljfwapp/sys/lwReportEpidemicStu/api/base/getUserDetailDB.do"
        res = requests.post(user_info_url, cookies=self.cookies).content.decode(
            encoding="utf-8")
        user_info = json.loads(res)
        assert "data" in user_info, "get userinfo failed"
        with open("./data/user.json", "w") as f:
            json.dump(user_info["data"], f)

        self.headers = {
            'Origin': 'http://eportal.uestc.edu.cn',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0',
        }

    def _get_tem_post_data(self, index):
        assert index >= 1 and index <= 3, "index must be 1,2 or 3"

        # fucking names，why client need to post
        display_names = ["早上", "中午", "晚上"]
        # data from user info
        user_info_keys = ["USER_ID", "USER_NAME", "DEPT_CODE", "DEPT_NAME"]
        data = {}
        with open("./data/user.json", 'r') as f:
            user = json.load(f)
            for key in user_info_keys:
                data[key] = user[key]

        # data we need to set various every day
        cur_date_str, time_str = get_date_str().split(" ")
        data['CREATED_AT'] = f'{cur_date_str} {time_str[:-3]}'
        data['NEED_DATE'] = cur_date_str
        data['DAY_TIME'] = str(index)
        data['DAY_TIME_DISPLAY'] = display_names[index-1]
        # !!! be careful, temperature must in [36.3,36.7]
        data['TEMPERATURE'] = "%.1f" % (random.uniform(36.3, 36.7))
        data['WID'] = ""
        return data

    def run(self):
        """ 一次性打完所有温度 """
        # TODO 按时打卡

        post_url = self.url
        # morning:1、noon:2、night:3
        for i in range(1, 4):
            post_data = self._get_tem_post_data(i)
            res = requests.post(post_url, data=post_data,
                                cookies=self.cookies, headers=self.headers)
            logging.debug("TEMPERATURE", post_data,
                          res.content.decode(encoding="utf-8"))
            # TODO  need to retry if fail

    def runable(self):
        # 判断上次打卡时间
        pass


class StuReportTask(Task):
    def __init__(self):
        super(StuReportTask, self).__init__()
        self.url = 'http://eportal.uestc.edu.cn/qljfwapp/sys/lwReportEpidemicStu/mobile/dailyReport/T_REPORT_EPIDEMIC_CHECKIN_YJS_SAVE.do'
        self.method = self.RequestMethod.POST
        self.last_run = 0
        self.data_path = 'data/report.json'
        self.cookies = {}
        self.init_data()

    def init_data(self):
        self.cookies = Login.load_cookies()
        lastest_daily_report_url = "http://eportal.uestc.edu.cn/qljfwapp/sys/lwReportEpidemicStu/mobile/dailyReport/getLatestDailyReportData.do"
        post_data = {
            "pageNum":1,
            "pageSize":10,
            "USER_ID":config.user
        }
        last_daily_data = requests.post(
            lastest_daily_report_url, data=post_data, cookies=self.cookies).content
        data = json.loads(last_daily_data)
        data = data["datas"]["getLatestDailyReportData"]["rows"][0]
        with open('./data/report.json', 'w') as f:
            json.dump(data, f)

    def _get_post_data(self):
        data = {}
        with open('./data/report.json', 'r') as f:
            data = json.load(f)
        # Normally we not need to change report data, just post lastest data
        cur_date_str, time_str = get_date_str().split(" ")
        data['CZRQ'] = cur_date_str+" 00:00:00"
        data['NEED_CHECKIN_DATE'] = cur_date_str
        data['CREATED_AT'] = get_date_str()
        wid = self._get_today_wid()
        data['WID'] = wid
        return data

    def _get_today_wid(self):
        self.cookies = Login.load_cookies()
        url = "http://eportal.uestc.edu.cn/qljfwapp/sys/lwReportEpidemicStu/mobile/dailyReport/getMyTodayReportWid.do"
        post_data = {
            "pageNum":"1",
            "pageSize":"10",
            "USER_ID":config.user,
        }
        res = requests.post(url, data=post_data, cookies=self.cookies).content
        data = json.loads(res)
        wid = data["datas"]["getMyTodayReportWid"]["rows"][0]["WID"]
        return wid
        
    def run(self):
        post_url = self.url
        data = self._get_post_data()
        headers = {
            'Origin': 'http://eportal.uestc.edu.cn',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0',

        }
        res = requests.post(post_url, data=data,
                            cookies=self.cookies, headers=headers)
        print(res.content.decode(encoding="utf-8"))

    def runable(self):
        now = time.time()


class UESTCPunch(object):
    def __init__(self, user, passwd):
        self.user = user
        self.passwd = passwd
        login = Login(self.user, self.passwd)

    def start(self):
        timer = threading.Timer(5, self.run, [], {})
        timer.start()

    def run(self):
        print("dd")


class MyThread(threading.Thread):
    def __init__(self, event):
        threading.Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(10):
            print("my thread")
            # call a function


if __name__ == "__main__":
    stu = StuReportTask()
    stu.run()
    tem = TemperatureTask()
    tem.run()
